import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';
import '../../../common/routers/names.dart';
import 'widgets/index.dart';

class HomeIndexController extends GetxController {
  HomeIndexController();

  // 服务器服务
  final ServerService _serverService = Get.find<ServerService>();

  // 服务器列表
  RxList<ServerModel> servers = <ServerModel>[].obs;
  
  // 分组列表
  RxList<ServerGroup> groups = <ServerGroup>[].obs;
  
  // 分组展开状态
  RxMap<String, bool> groupExpandedStates = <String, bool>{}.obs;

  // 是否正在加载
  RxBool isLoading = false.obs;

  // 状态监听订阅
  StreamSubscription<ServerModel>? _stateSubscription;

  @override
  void onInit() {
    super.onInit();
    loadServers();
    loadGroups();
    _listenToServerStateChanges();
  }

  /// 监听服务器状态变化 - 关键：实现实时同步
  void _listenToServerStateChanges() {
    debugPrint('👂 HomeIndexController: 开始监听服务器状态变化');
    _stateSubscription = _serverService.serverStateStream.listen((updatedServer) {
      debugPrint('📢 HomeIndexController: 收到服务器状态更新 - ${updatedServer.name}: ${updatedServer.status.displayName}');
      
      // 更新列表中的服务器状态
      final index = servers.indexWhere((s) => s.id == updatedServer.id);
      if (index != -1) {
        servers[index] = updatedServer;
        debugPrint('✅ HomeIndexController: 列表中的服务器状态已更新');
      } else {
        // 新添加的服务器
        servers.add(updatedServer);
        debugPrint('✅ HomeIndexController: 新服务器已添加到列表');
      }
    });
  }

  /// 加载服务器列表
  void loadServers() {
    servers.value = _serverService.getAllServers();
    update(["home_index"]);
  }
  
  /// 加载分组列表
  void loadGroups() {
    groups.value = _serverService.getAllGroups();
    // 初始化所有分组为展开状态
    for (final group in groups) {
      if (!groupExpandedStates.containsKey(group.id)) {
        groupExpandedStates[group.id] = true;
      }
    }
  }
  
  /// 切换分组展开/折叠
  void toggleGroupExpanded(String groupId) {
    groupExpandedStates[groupId] = !(groupExpandedStates[groupId] ?? true);
  }
  
  /// 获取分组中的服务器
  List<ServerModel> getServersByGroup(String? groupId) {
    return servers.where((s) => s.groupId == groupId).toList();
  }
  
  /// 获取未分组的服务器
  List<ServerModel> getUngroupedServers() {
    return servers.where((s) => s.groupId == null || s.groupId!.isEmpty).toList();
  }

  /// 刷新列表
  Future<void> onRefresh() async {
    await Future.delayed(const Duration(milliseconds: 500));
    loadServers();
    loadGroups();
  }

  /// 打开服务器详情
  void openServerDetail(ServerModel server) {
    Get.toNamed(RouteNames.homeServerDetail, parameters: {'id': server.id});
  }

  /// 显示添加服务器表单
  void showAddServerForm() {
    debugPrint('🎯 HomeIndexController: 显示添加服务器表单');
    
    Get.bottomSheet(
      AddServerForm(
        onSubmit: _addServer,
      ),
      isScrollControlled: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
    );
  }

  /// 显示编辑服务器表单
  void showEditServerForm(ServerModel server) {
    debugPrint('✏️ HomeIndexController: 显示编辑服务器表单');
    debugPrint('   服务器: ${server.name}');
    
    Get.bottomSheet(
      ServerForm(
        server: server,
        onSubmit: ({
          required String name,
          required String host,
          required int port,
          required String username,
          String? password,
          String? privateKey,
          String? groupId,
        }) => _editServer(
          server: server,
          name: name,
          host: host,
          port: port,
          username: username,
          password: password,
          privateKey: privateKey,
          groupId: groupId,
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
    );
  }

  /// 显示分组管理对话框
  void showGroupManagement() {
    Get.bottomSheet(
      _GroupManagementSheet(controller: this),
      isScrollControlled: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
    );
  }
  
  /// 创建分组
  Future<void> createGroup(String name, {String? description}) async {
    try {
      LoadingUtil.show('正在创建分组...');
      await _serverService.createGroup(name: name, description: description);
      LoadingUtil.success('分组创建成功');
      loadGroups();
    } catch (e) {
      LoadingUtil.error('创建失败: $e');
    }
  }
  
  /// 删除分组
  Future<void> deleteGroup(ServerGroup group) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除分组 "${group.name}" 吗？\n\n该分组下的服务器将移至"默认分组"。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
    
    if (confirmed == true) {
      try {
        LoadingUtil.show('正在删除分组...');
        await _serverService.deleteGroup(group.id);
        LoadingUtil.success('分组删除成功');
        loadGroups();
        loadServers(); // 刷新服务器列表
      } catch (e) {
        LoadingUtil.error('删除失败: $e');
      }
    }
  }

  /// 添加服务器
  Future<void> _addServer({
    required String name,
    required String host,
    required int port,
    required String username,
    String? password,
    String? privateKey,
    String? groupId,
  }) async {
    debugPrint('➕ HomeIndexController: 开始添加服务器');
    debugPrint('   名称: $name');
    debugPrint('   地址: $host:$port');
    debugPrint('   用户名: $username');
    debugPrint('   密码长度: ${password?.length ?? 0}');
    
    try {
      LoadingUtil.show('正在添加...');

      await _serverService.addServer(
        name: name,
        host: host,
        port: port,
        username: username,
        password: password,
        privateKey: privateKey,
        groupId: groupId,
      );

      debugPrint('✅ HomeIndexController: 服务器添加成功');
      LoadingUtil.success('添加成功');
      Get.back(); // 关闭底部表单
      loadServers(); // 刷新列表
    } catch (e) {
      debugPrint('❌ HomeIndexController: 添加服务器失败 - $e');
      LoadingUtil.error('添加失败: $e');
    }
  }

  /// 编辑服务器
  Future<void> _editServer({
    required ServerModel server,
    required String name,
    required String host,
    required int port,
    required String username,
    String? password,
    String? privateKey,
    String? groupId,
  }) async {
    debugPrint('✏️ HomeIndexController: 开始编辑服务器');
    debugPrint('   原名称: ${server.name} → 新名称: $name');
    debugPrint('   地址: $host:$port');
    debugPrint('   用户名: $username');
    debugPrint('   是否修改密码: ${password != null && password.isNotEmpty}');
    
    try {
      LoadingUtil.show('正在保存...');

      // 构建更新后的服务器对象
      final updatedServer = server.copyWith(
        name: name,
        host: host,
        port: port,
        username: username,
        password: password != null && password.isNotEmpty ? password : server.password,
        privateKey: privateKey,
        groupId: groupId,
      );

      await _serverService.updateServer(updatedServer);

      debugPrint('✅ HomeIndexController: 服务器编辑成功');
      LoadingUtil.success('保存成功');
      Get.back(); // 关闭底部表单
      loadServers(); // 刷新列表
    } catch (e) {
      debugPrint('❌ HomeIndexController: 编辑服务器失败 - $e');
      LoadingUtil.error('保存失败: $e');
    }
  }

  @override
  void onClose() {
    debugPrint('🔚 HomeIndexController: onClose - 取消状态监听');
    _stateSubscription?.cancel();
    super.onClose();
  }
}

/// 分组管理 Sheet
class _GroupManagementSheet extends StatelessWidget {
  final HomeIndexController controller;
  
  const _GroupManagementSheet({required this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部把手
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.only(bottom: 16),
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          // 标题
          Row(
            children: [
              const Text(
                '分组管理',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const Spacer(),
              TextButton.icon(
                onPressed: () => _showAddGroupDialog(context),
                icon: const Icon(Icons.add, size: 18),
                label: const Text('新建分组'),
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          // 分组列表
          Obx(() {
            if (controller.groups.isEmpty) {
              return const Padding(
                padding: EdgeInsets.all(32),
                child: Text('还没有分组\n点击右上角"新建分组"创建', textAlign: TextAlign.center),
              );
            }
            
            return ListView.builder(
              shrinkWrap: true,
              itemCount: controller.groups.length,
              itemBuilder: (context, index) {
                final group = controller.groups[index];
                final serverCount = controller.getServersByGroup(group.id).length;
                
                return ListTile(
                  leading: const Icon(Icons.folder, color: Colors.blue),
                  title: Text(group.name),
                  subtitle: Text('$serverCount 台服务器'),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete_outline, color: Colors.red),
                    onPressed: () => controller.deleteGroup(group),
                  ),
                );
              },
            );
          }),
        ],
      ),
    );
  }

  void _showAddGroupDialog(BuildContext context) {
    final nameController = TextEditingController();
    
    Get.dialog(
      AlertDialog(
        title: const Text('新建分组'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '分组名称',
            hintText: '请输入分组名称',
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final name = nameController.text.trim();
              if (name.isNotEmpty) {
                Get.back();
                Get.back(); // 关闭 bottom sheet
                controller.createGroup(name);
              }
            },
            child: const Text('创建'),
          ),
        ],
      ),
    );
  }
}

